﻿using System;
using System.Collections.Generic;
//using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Chat_D_LuX_Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private delegate void HandleBroadcastCallback(object sender, EventArgs e);
        public void HandleBroadcast(object sender, EventArgs e)
        {
            
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new HandleBroadcastCallback(HandleBroadcast), sender, e);
            }
            else
            {
                try
                {
                    System.DateTime nowtime = new System.DateTime();
                    nowtime = System.DateTime.Now;

                    var eventData = (BroadcastorServiceRef.EventDataType)sender;
                    Controls.ucMessage tempobject = new Controls.ucMessage() { MessageText = eventData.EventMessage, IsAltColor = _currentColor, User = eventData.User.Username, Timestamp = nowtime.Hour.ToString() + ":" + nowtime.Minute.ToString()};

                    lbChatbox.Items.Add(tempobject);
                    if (_currentColor)
                    {
                        _currentColor = false;
                    }
                    else
                    {
                        _currentColor = true;
                    }
                    lbChatbox.ScrollIntoView(tempobject);

                    //MessageBox.Show(eventData.EventMessage + " " + eventData.ClientID);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private BroadcastorServiceRef.BroadcastorServiceClient _client;
        private BroadcastorServiceRef.User _bsruser = new BroadcastorServiceRef.User();
        private ChatServiceRef.User _csruser;

        public MainWindow(ChatServiceRef.User User)
        {
            ChatServiceRef.Chat_ServiceClient sr = new ChatServiceRef.Chat_ServiceClient();
            _bsruser.PkId = User.PkId;
            _bsruser.Username = User.Username;
            _bsruser.Email = User.Email;
            _bsruser.IsActive = User.IsActive;
            _bsruser.IsAdmin = User.IsAdmin;

            // Register client to broadcast service.
            this.RegisterClient();

            InitializeComponent();

            // Get all the rooms from the database
            DataTable dt = sr.GetRooms();
            // 
            foreach (DataRow r in dt.Rows)
            {
                // Details for room
                Controls.ucRoom room = new Controls.ucRoom(
                    Convert.ToInt64(r["pkID"].ToString()),
                    r["RoomName"].ToString(),
                    r["Description"].ToString());
                // put ucRoom into wrap panel
                //wpRooms.Children.Add(room);

                // Put ucRoom into Lobby grid
                lbLobby.Items.Add(room);

                // Set event handler for user control
                room.JoinRoom += new EventHandler(room_JoinRoom);
            }
        }

        private void RegisterClient()
        {
            if ((this._client != null))
            {
                this._client.Abort();
                this._client = null;
            }

            BroadcastorCallback cb = new BroadcastorCallback();
            cb.SetHandler(this.HandleBroadcast);

            System.ServiceModel.InstanceContext context =
                new System.ServiceModel.InstanceContext(cb);
            this._client =
                new BroadcastorServiceRef.BroadcastorServiceClient(context);
            
            this._client.RegisterClient(_bsruser);
        }

        private void mnuEditProfile_Click(object sender, RoutedEventArgs e)
        {
            var newAccountEdit = new AccountEdit(_csruser);
            newAccountEdit.ShowDialog();
        }

        private void mnuCreateRoom_Click(object sender, RoutedEventArgs e)
        {
            // Variable to hold room info
            long roomId;
            string roomName;
            string roomDescription;

            // Room object
            BroadcastorServiceRef.Room bsrRoom = new BroadcastorServiceRef.Room();

            // Create Room showdialog
            var frmCreateRoom = new CreateRoom();
            var result = frmCreateRoom.ShowDialog();
            if (result.Value)
            {
                //get room info from from database
                ChatServiceRef.Chat_ServiceClient sr = new ChatServiceRef.Chat_ServiceClient();
                DataTable dt = sr.GetRoomDetails(frmCreateRoom.roomName);

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow r in dt.Rows)
                    {
                        roomId = Convert.ToInt64(r["pkID"].ToString());
                        roomName = r["RoomName"].ToString();
                        roomDescription = r["Description"].ToString();
                    }
                }

                


                // Broadcast new room
                if (this._client == null)
                {
                    MessageBox.Show(this, "Client is not registered");
                    return;
                }
                this._client.NotifyServer(
                    new BroadcastorServiceRef.EventDataType()
                    {
                        ClientID = _bsruser.PkId,
                        EventMessage = "Test message."
                    });

            }




            
            ////send room object
            //var newCreateRoom = new CreateRoom();
            //newCreateRoom.ShowDialog();

            ////check for null room object
            ////take room and set into tab
            ////tbcMain.Items.Add();

            
        }

        private void mnuTest_Click(object sender, RoutedEventArgs e)
        {
            if (this._client == null)
            {
                MessageBox.Show(this, "Client is not registered");
                return;
            }
            this._client.NotifyServer(
                new BroadcastorServiceRef.EventDataType()
                {
                    ClientID = _bsruser.PkId,
                    EventMessage = "Test message."
                });
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        protected void room_JoinRoom(object sender, EventArgs e)
        {
            
        }

        private bool _currentColor = false;
        private void btnMessage_Click(object sender, RoutedEventArgs e)
        {
            if (this._client == null)
            {
                MessageBox.Show(this, "Client is not registered");
                return;
            }
            this._client.NotifyServer(
                new BroadcastorServiceRef.EventDataType()
                {
                    ClientID = _bsruser.PkId,
                    EventMessage = txtMessage.Text,
                    User = _bsruser
                });

            System.DateTime nowtime = new System.DateTime();
            nowtime = System.DateTime.Now;

            //scrape textboxt text and fill message
            Controls.ucMessage tempobject = new Controls.ucMessage() { MessageText = txtMessage.Text, IsAltColor = _currentColor, User = _bsruser.Username, Timestamp = nowtime.Hour.ToString() + ":" + nowtime.Minute.ToString()};

            lbChatbox.Items.Add(tempobject);
            if (_currentColor)
            {
                _currentColor = false;
            }
            else
            {
                _currentColor = true;
            }
            lbChatbox.ScrollIntoView(tempobject);
            txtMessage.Clear();
            txtMessage.Focus();

        }

        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    var newRegisterWindow = new Register();
        //    newRegisterWindow.Show();
        //}

        //private void Button_Click_1(object sender, RoutedEventArgs e)
        //{
        //    var newLoginWindow = new Login();
        //    newLoginWindow.Show();
        //}
    }
}
